import { MenuOutlined } from '@ant-design/icons';
import { Table, Checkbox, Modal, Button, Col, InputNumber, Row, Slider } from 'antd';
import { arrayMoveImmutable } from 'array-move';
import React, { useState, useEffect } from 'react';
import './sortable.css'
import { SortableContainer, SortableElement, SortableHandle } from 'react-sortable-hoc';
import { index } from 'mathjs';

Storage = window.localStorage
/**
 * @param {array} tableColum  列头数据  例如 const coloumArray=[{ title: "序号", key: "xuhao",show:true}]
 * @param {Function} handleTableColum 这个就是处理列表数据的函数
 * @param {string} stroageName 本地仓库变量名称
 * @param {boolean} open 控制弹窗是否显示
 * @param {Function} handleOpen 这个就是处理是否显示数据的函数
 * @param {number} initSize 初始大小
 * @param {Function}  handleIntisize 这个就是处理初始table大小的函数
 * @param {*} props 
 * @returns 
 */
const Sortable = (props) => {
  const [tableColoumList, setTableColoumList] = useState([])
  const [isModalOpen, setIsModalOpen] = useState();
  const [inputValue, setInputValue] = useState(props.initSize ? parseFloat(props.initSize) : 1);
  //判断两个对象是否相等
  function deepEqual(obj1, obj2) {
    // 首先检查两个对象是否都是对象且不是null  
    if (typeof obj1 !== 'object' || obj1 === null || typeof obj2 !== 'object' || obj2 === null) {
      // 如果它们不是对象或其中一个是null，则直接比较它们是否严格相等  
      return obj1 === obj2;
    }

    // 获取两个对象的所有可枚举属性名  
    const keys1 = Object.keys(obj1);
    const keys2 = Object.keys(obj2);

    // 如果属性名数量不同，则它们不相等  
    if (keys1.length !== keys2.length) {
      return false;
    }

    // 检查每个属性名和对应的值是否都相等  
    for (const key of keys1) {
      // 如果第二个对象没有这个键，则它们不相等  
      if (!(key in obj2)) {
        return false;
      }

      // 递归比较属性值  
      if (!deepEqual(obj1[key], obj2[key])) {
        return false;
      }
    }

    // 如果所有检查都通过，则它们相等  
    return true;
  }


  useEffect(() => {
    setTableColoumList(props.tableColnum)
  }, [props.storageName])

  useEffect(() => {
    setIsModalOpen(props.open)
  }, [props.open])
  useEffect(() => {
    setInputValue(props.initSize)
  }, [props.initSize])

  const data = []
  if (Storage[props.storageName]) {
    var arr = JSON.parse(Storage[props.storageName])
    // console.log(arr, "11");
    var result = false
    if (arr.length === props.tableColnum.length) {
      let areObjectsEqual = (obj1, arr) => {
        //返回obj2
        let arr2 = arr.filter(obj2 =>
          obj2.key === obj1.key
        )
        //不存在
        if (arr2.length == 0) {
          // console.log("不存在某个属性");
          return false
        }
        else {
          let keys = Object.keys(arr2[0]).filter(key => key !== 'index' && key !== 'show' )
          let keys2 = Object.keys(obj1).filter(key => key !== 'index' && key !== 'show')
          // console.log(arr2[0], obj1, keys, keys2);
          //多一个index
          if (keys.length == keys2.length) {
            // console.log("对象属性之间长度一致");
            let flag = true
            // 遍历第一个对象的所有键，检查值是否相同  
            for (const key of keys) {
              // 如果第二个对象没有这个键或者两个值不相等,则返回false  
              // if (!(key in obj1) || !deepEqual(arr2[0][key], obj1[key])) {
              //   console.log(key in obj1, arr2[0][key] !== obj1[key], arr2[0], obj1);
              //   console.log(key,"属性值不一致");
              //   flag = false;
              // }
              // 如果第二个对象没有这个键则返回false  
              if (!(key in obj1)) {
                // console.log(key in obj1, arr2[0][key] !== obj1[key], arr2[0], obj1);
                // console.log(key,"属性值不一致");
                flag = false;
              }

            }
            return flag;
          }
          else {
            // console.log("对象属性之间长度不一致");
            return false
          }
        }
      }
      // let isSame = (obj1, obj2) => obj1.key === obj2.key;
      result = props.tableColnum.every(obj1 => {
        return areObjectsEqual(obj1, arr);
      });
    }
    else { result = false }
    // console.log(result, "result");
    if (result) {
      props.tableColnum.forEach(obj1 => {
        let obj2 = arr.find(obj => obj.key === obj1.key);
        if (obj2) {
          obj2.title = obj1.title;// 这里将array2中对应对象的值修改为array1中对象的值
          if (obj1.style) {
            obj2.style = obj1.style;
          }
        }
      });
      // console.log("有本地存储且长度一样", arr)
      for (let i = 0; i < arr.length; i++) {
        let item = { ...arr[i], index: i }
        data.push(item)
      }
      // console.log("有本地存储且长度一样", data)
      Storage[props.storageName] = JSON.stringify(data)
    }
    else {
      arr.forEach(obj1 => {
        let obj2 = props.tableColnum.find(obj => obj.key === obj1.key);
        if (obj2) {
          obj2 = obj1; // 这里将array2中对应对象的值修改为array1中对象的值  
        }
      });
      // //console.log("无本地存储且长度一样", props.tableColnum)
      for (let i = 0; i < props.tableColnum.length; i++) {
        let item = { ...props.tableColnum[i], index: i }
        data.push(item)
      }
      // console.log("有本地存储且长度不一样", data)
      Storage[props.storageName] = JSON.stringify(data)
      props.handleTableColomn(data)
    }

  }
  else {
    // //console.log("无本地存储",props.tableColnum)
    Storage[props.storageName] = JSON.stringify(props.tableColnum)
    for (let i = 0; i < props.tableColnum.length; i++) {
      let item = { key: props.tableColnum[i].key, title: props.tableColnum[i].title, show: true, index: i }
      data.push(item)
    }
  }

  const [dataSource, setDataSource] = useState(data);

  const DragHandle = SortableHandle(() => (
    <MenuOutlined
      style={{
        cursor: 'grab',
        color: '#999',
      }}
    />
  ));


  const SortableItem = SortableElement((props) => <tr {...props} />);
  const SortableBody = SortableContainer((props) => <tbody {...props} />);

  const DraggableContainer = (props) => (
    <SortableBody
      useDragHandle
      disableAutoscroll
      helperClass="row-dragging"
      onSortEnd={onSortEnd}
      {...props}
    />
  );
  const onSortEnd = ({ oldIndex, newIndex }) => {
    if (oldIndex !== newIndex) {
      const newData = arrayMoveImmutable(dataSource.slice(), oldIndex, newIndex).filter(
        (el) => !!el,
      );

      var resultdata = newData.map(obj => {
        if (obj.show) {
          return { ...obj };
        }
        else return obj
      })
      // var filterdata = resultdata.filter(item => item.show === true)
      // console.log(filterdata, "filterdata");
      props.handleTableColomn(resultdata)
      Storage[props.storageName] = JSON.stringify(resultdata)
      setDataSource(newData);
    }
  };
  const onChange = (e, record) => {
    var changedList = dataSource.map(obj => {
      if (obj.key === record.key) {
        return { ...obj, show: !record.show };
      } else {
        return obj;
      }
    })
    setDataSource(changedList)
    // var filterdata = changedList.filter(item =>
    //   item.show === true
    // )
    Storage[props.storageName] = JSON.stringify(changedList)
    props.handleTableColomn(changedList)
  };

  const handleClick = () => {
    var changedList = dataSource.map(obj => {
      return { ...obj, show: true }
    })
    setDataSource(changedList)
    Storage[props.storageName] = JSON.stringify(changedList)
    props.handleTableColomn(changedList)
  }
  const columns = [
    {
      title: '排序',
      dataIndex: 'sort',
      width: 60,
      className: 'drag-visible',
      render: () => <DragHandle />,
    },
    {
      title: '列名称',
      dataIndex: 'title',
      className: 'drag-visible',
    },
    {
      title: <div>是否显示   <Button onClick={handleClick} type='primary' size='small'>全选</Button></div>,
      dataIndex: 'show',
      render: (text, record, index) => <Checkbox onChange={e => { onChange(e, record) }} checked={text}></Checkbox>,
    }
  ];

  const handleOk = () => {
    props.handleOpen(false)
  };
  const handleCancel = () => {
    props.handleOpen(false)
  };


  const onSliderChange = (newValue) => {
    newValue == null ? newValue = 1 : ""
    props.handleInitSize(newValue)
  };

  const DraggableBodyRow = ({ className, style, ...restProps }) => {
    // function findIndex base on Table rowKey props and should always be a right array index
    const index = dataSource.findIndex((x) => x.index === restProps['data-row-key']);
    return <SortableItem index={index} {...restProps} />;
  };

  return (
    <Modal title="动态列设置" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
      {props.initSize && (<Row style={{ marginBottom: 10 }} align="middle">
        <Col span={4}>
          <span>表格宽度</span>
        </Col>
        <Col span={12}>
          <Slider
            min={0.4}
            max={1.4}
            onChange={onSliderChange}
            value={inputValue}
            step={0.01}
          />
        </Col>
        <Col span={4}>
          <InputNumber
            min={0.4}
            max={1.4}
            style={{
              margin: '0 14px',
            }}
            step={0.01}
            value={inputValue}
            onChange={onSliderChange}
          />
        </Col>
      </Row>)}
      <Table
        pagination={false}
        dataSource={dataSource}
        columns={columns}
        rowKey="index"
        components={{
          body: {
            wrapper: DraggableContainer,
            row: DraggableBodyRow,
          },
        }}
      />

    </Modal>
  );
};
export default Sortable;
